package com.dynamic.idea.quick.develop.plugin.dialog;

import com.dynamic.idea.quick.develop.plugin.dialog.child.RequestParameterDialogWrapper;
import com.dynamic.idea.quick.develop.plugin.entity.base02.*;
import com.dynamic.idea.quick.develop.plugin.entity.base02.model.ImportStruct;
import com.dynamic.idea.quick.develop.plugin.entity.base02.model.RequestParamStruct;
import com.dynamic.idea.quick.develop.plugin.enums.GeneralPackageStructTypeEnums;
import com.dynamic.idea.quick.develop.plugin.utils.*;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.panel.ComponentPanelBuilder;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import com.intellij.psi.impl.file.PsiJavaDirectoryFactory;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlText;
import com.intellij.ui.SingleSelectionModel;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.fields.ExpandableTextField;
import com.intellij.ui.components.fields.ExtendableTextComponent;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UI;
import com.intellij.util.ui.UIUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Model;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.*;

public class QuickDevelopStartDialogWrapper02 extends DialogWrapper {

    // 请求参数列表名->结构映射数据
    private Map<String,RequestParamStruct> requestParamName2StructDataMap=null;

    private Project project;

    // 请求参数的列表model
    private CollectionListModel requestParameterDataModel =null;

    // 文本输入框大小
    private static final int FIELD_SIZE=30;

    // 类名
    private JTextField classNameJTextField =null;
    // 方法名
    private JTextField methodNameJTextField =null;
    // 注释
    private JTextField commentJTextField =null;

    // 请求参数列表
    private JList requestParameterJList=null;

    // 返回数据
    private RequestParamStruct returnParamStruct=null;

    // 请求参数数据
//    private List<String> requestParameterDataList=new ArrayList<>();

    public QuickDevelopStartDialogWrapper02(Project project) {
        super(true); // use current window as parent
        this.project=project;

        setTitle("Quick Develop Starting");
        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {

        // 请求参数类型数据
        requestParamName2StructDataMap=new LinkedHashMap<>();

        //类名
        classNameJTextField =new JTextField(FIELD_SIZE);
        //方法名
        methodNameJTextField =new JTextField(FIELD_SIZE);

        //注释
        commentJTextField =new JTextField(FIELD_SIZE);

        // 请求参数列表
        requestParameterDataModel = new CollectionListModel();
        requestParameterJList = new JBList(requestParameterDataModel);// 创建指定列名和数据的表格
        requestParameterJList.setSelectionModel(new SingleSelectionModel());

        ToolbarDecorator decorator = ToolbarDecorator.createDecorator(requestParameterJList);

        // "添加"相应
        addRequestParameterAction(decorator);

        // 移除 相应的数据
        removeRequestParameterAction(decorator);

        // 编辑相应
        editRequestParameterAction(decorator);

        // 上移
//        moveUpRequestParameterAction(decorator);
        // 下移
//        moveDownRequestParameterAction(decorator);

        JPanel pane = decorator.createPanel();
        pane.setPreferredSize(JBUI.size(0, 140));
        pane.putClientProperty(UIUtil.KEEP_BORDER_SIDES, SideBorder.ALL);

        ComponentPanelBuilder componentPanelBuilder = UI.PanelFactory.panel(pane).
                withLabel("requestParameter")
                .resizeY(true);

        //测试数据
//        classNameJTextField.setText("BillOrder2");
//        methodNameJTextField.setText("test01");

        ExpandableTextField expandableTextField=new ExpandableTextField();

//        ExtendableTextComponent.Extension addBrowseExtension =
//                ExtendableTextComponent.Extension.create(AllIcons.General.InlineAdd, AllIcons.General.InlineAdd,
//                        "Add", () -> System.out.println("Browse file clicked"));

        ExtendableTextComponent.Extension editBrowseExtension =
                ExtendableTextComponent.Extension.create(AllIcons.General.Inline_edit, AllIcons.General.Inline_edit,
                        "Edit", () -> {
                    System.out.println("Browse file clicked");
                    RequestParameterDialogWrapper remoteRepositoriesDialogWrapper = new RequestParameterDialogWrapper(project,"returnEdit",null,returnParamStruct);
                    if (remoteRepositoriesDialogWrapper.showAndGet()) {
                        RequestParamStruct requestParamStruct = remoteRepositoriesDialogWrapper.getRequestParamStruct();
                        returnParamStruct=requestParamStruct;
                        if (requestParamStruct!=null){
                            expandableTextField.setText(returnParamStruct.showSimpleName());
                        }
                    }
                });


//        expandableTextField.addExtension(addBrowseExtension);
        expandableTextField.addExtension(editBrowseExtension);
//        expandableTextField.setBorder(null);


        JPanel p = UI.PanelFactory.grid()
                .add(UI.PanelFactory.panel(classNameJTextField).withLabel("className:"))
                .add(UI.PanelFactory.panel(methodNameJTextField).withLabel("methodName:"))
                .add(UI.PanelFactory.panel(commentJTextField).withLabel("comment:"))
                .add(componentPanelBuilder)
                .add(UI.PanelFactory.panel(expandableTextField).withLabel("return:"))
                .createPanel();

        return p;
    }

    // 请求参数列表的 增加按钮相应
    private void addRequestParameterAction(ToolbarDecorator decorator){
        //增加添加
        decorator.setAddAction(new AnActionButtonRunnable() {
            @Override
            public void run(AnActionButton anActionButton) {
//                adjustModelData();
                //弹出Table框
                System.out.println("===add====");
                RequestParameterDialogWrapper remoteRepositoriesDialogWrapper = new RequestParameterDialogWrapper(project,"add",requestParamName2StructDataMap,null);
                if (remoteRepositoriesDialogWrapper.showAndGet()) {
                    // user pressed OK
                    RequestParamStruct requestParamStruct = remoteRepositoriesDialogWrapper.getRequestParamStruct();
//                    String className = StringUtils.trim(requestParamStruct.getClassName());
                    String paramName = StringUtils.trim(requestParamStruct.getParamName());
                    requestParameterDataModel.add(requestParamStruct.showSimpleNameParam());
                    requestParamName2StructDataMap.put(paramName,requestParamStruct);

//                    requestParameterJList.setListData(requestParameterDataList.toArray());

//                    requestParamStruct.getSuperClassStructList()
//                    RemoteRepositoryModel remoteRepositoryModel = remoteRepositoriesDialogWrapper.getRemoteRepositoryModel();
//                    if (remoteRepositoryModel!=null){
//                        System.out.println(JSON.toJSONString(remoteRepositoryModel));
//
//                        dataModel.add(remoteRepositoryModel.getUrl());
//                        url2RemoteRepositoryModelMap.put(remoteRepositoryModel.getUrl(),remoteRepositoryModel);
//                    }

                }
            }
        });
    }


    // 请求参数列表的 移除按钮相应
    private void removeRequestParameterAction(ToolbarDecorator decorator){
        //增加添加
        decorator.setRemoveAction(new AnActionButtonRunnable() {
            @Override
            public void run(AnActionButton anActionButton) {
//                adjustModelData();
                //弹出Table框
                System.out.println("===remove====");
                Object selectedValue = requestParameterJList.getSelectedValue();
                if (selectedValue==null){
                    return;
                }
                String selectStr=(String)selectedValue;
                if (StringUtils.isBlank(selectStr)){
                    return;
                }

                String selectParameterName = StringUtils.trim(StringUtils.substringAfter(selectStr, " "));

                int selectedIndex = requestParameterJList.getSelectedIndex();

                requestParameterDataModel.remove(selectedIndex);

                Set<Map.Entry<String, RequestParamStruct>> entries = requestParamName2StructDataMap.entrySet();
                Iterator<Map.Entry<String, RequestParamStruct>> iterator = entries.iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, RequestParamStruct> next1 = iterator.next();
                    String key = next1.getKey();

                    if (StringUtils.isBlank(key)){
                        continue;
                    }
                    //若是之前的url
                    if (StringUtils.equals(StringUtils.trimToEmpty(key),StringUtils.trimToEmpty(selectParameterName))){
                        iterator.remove();
                    }
                }

            }
        });
    }

    // 请求参数列表的 编辑按钮相应
    private void editRequestParameterAction(ToolbarDecorator decorator){
        //增加添加
        decorator.setEditAction(new AnActionButtonRunnable() {
            @Override
            public void run(AnActionButton anActionButton) {
//                adjustModelData();
                //弹出Table框
                System.out.println("===edit====");
                Object selectedValue = requestParameterJList.getSelectedValue();
                if (selectedValue==null){
                    return;
                }
                String selectStr=(String)selectedValue;
                if (StringUtils.isBlank(selectStr)){
                    return;
                }
                int selectedIndex = requestParameterJList.getSelectedIndex();

                String selectParameterName = StringUtils.trim(StringUtils.substringAfter(selectStr, " "));
                RequestParamStruct nowRequestParamStruct = requestParamName2StructDataMap.get(selectParameterName);

                RequestParameterDialogWrapper remoteRepositoriesDialogWrapper = new RequestParameterDialogWrapper(project,"edit",requestParamName2StructDataMap,nowRequestParamStruct);

                if (remoteRepositoriesDialogWrapper.showAndGet()) {
                    // user pressed OK
                    RequestParamStruct requestParamStruct = remoteRepositoriesDialogWrapper.getRequestParamStruct();
//                    String className = StringUtils.trim(requestParamStruct.getClassName());
                    String paramName = StringUtils.trim(requestParamStruct.getParamName());
                    requestParameterDataModel.setElementAt(requestParamStruct.showSimpleNameParam(),selectedIndex);

//                    requestParameterDataModel.add(className+" "+paramName);

                    Map<String,RequestParamStruct> newRequestParamName2StructDataMap=new LinkedHashMap<>();

                    Set<Map.Entry<String, RequestParamStruct>> entries = requestParamName2StructDataMap.entrySet();


                    Iterator<Map.Entry<String, RequestParamStruct>> iterator = entries.iterator();

                    while (iterator.hasNext()){
                        Map.Entry<String, RequestParamStruct> next1 = iterator.next();
                        String key = next1.getKey();

                        if (StringUtils.isBlank(key)){
                            continue;
                        }
                        //若是之前的url
                        if (StringUtils.equals(StringUtils.trimToEmpty(key),StringUtils.trimToEmpty(selectParameterName))){
//                            iterator.remove();
                            newRequestParamName2StructDataMap.put(paramName,requestParamStruct);
                        }else {
                            newRequestParamName2StructDataMap.put(key,requestParamName2StructDataMap.get(key));
                        }
                    }

                    requestParamName2StructDataMap=newRequestParamName2StructDataMap;
                }
            }
        });
    }

   /* // 请求参数列表的 上移按钮相应
    private void moveUpRequestParameterAction(ToolbarDecorator decorator){
        //增加添加
        decorator.setMoveUpAction(new AnActionButtonRunnable() {
            @Override
            public void run(AnActionButton anActionButton) {
                System.out.println("move up");
                reloadRequestParamData();
            }
        });
    }
    // 请求参数列表的 下移按钮相应
    private void moveDownRequestParameterAction(ToolbarDecorator decorator){
        //增加添加
        decorator.setMoveDownAction(new AnActionButtonRunnable() {
            @Override
            public void run(AnActionButton anActionButton) {
                System.out.println("move down");
                reloadRequestParamData();
            }
        });
    }
*/

    /**
     * 重新加载请求数据
     */
    private void reloadRequestParamData(){
        if (requestParameterDataModel==null){
            return;
        }
        List<String> items = requestParameterDataModel.getItems();
        if (CollectionUtils.isEmpty(items)){
            return;
        }
        Map<String,RequestParamStruct> requestParamName2StructDataMap2=new LinkedHashMap<>();
        for(String item:items){
            String selectParameterName = StringUtils.trim(StringUtils.substringAfter(item, " "));
            requestParamName2StructDataMap2.put(selectParameterName,requestParamName2StructDataMap.get(selectParameterName));
        }
        requestParamName2StructDataMap=requestParamName2StructDataMap2;
    }

    // 请求参数列表的 删除按钮的相应

    @Override
    protected void doOKAction() {
        super.doOKAction();

        reloadRequestParamData();

        // 类名
        String className= StringUtils.trim(classNameJTextField.getText());

        // 方法名
        String methodName=StringUtils.trim(methodNameJTextField.getText());

        String basePath=project.getBasePath();

        String pomFile=basePath+"/pom.xml";

        Model mavenModel = ModulesUtils.getMavenModel(pomFile);

        String projectName = mavenModel.getName();
        //项目地址
//        GeneralProjectStruct generalProjectStruct = GeneralRuleUtils.getProjectStructByName(projectName);
//        generalProjectStruct.setRootPath(basePath);

//        GeneralRule generalRule = GeneralRuleUtils.getOrderProviderGeneralRule(projectName, className, methodName);
        List<GeneralRule> generalRuleList = GeneralRuleUtils.getProjectGeneralRuleList(projectName, className, methodName);
        // 未设置配置信息
        if (CollectionUtils.isEmpty(generalRuleList)){
            NotifyUtils.notifyWarning("the "+projectName+" not set config info");
            return;
        }

        //请求参数结构列表
        List<RequestParamStruct> requestParamStructList=new ArrayList<>();
        if (MapUtils.isNotEmpty(requestParamName2StructDataMap)){
            for (String param: requestParamName2StructDataMap.keySet()){
                RequestParamStruct requestParamStruct = requestParamName2StructDataMap.get(param);
                requestParamStructList.add(requestParamStruct);
            }
        }

//        System.out.println(JSON.toJSONString(generalRule,true));

        // 生成
        GlobalSearchScope projectSearchScope=GlobalSearchScope.projectScope(project);
        GlobalSearchScope allSearchScope=GlobalSearchScope.allScope(project);

        // 项目结构
//        GeneralProjectStruct projectStruct = generalRule.getProjectStruct();
//        String rootPath = projectStruct.getRootPath();
//        System.out.println("rootPath:"+rootPath);


        WriteCommandAction.runWriteCommandAction(project, new Runnable() {

            @Override
            public void run() {
                for(GeneralRule generalRule:generalRuleList){

                    //1.根据包结构查询包是否存在

                    //2.根据类结构查询类是否存在
//                PsiClass providerClass = JavaPsiFacade.getInstance(project).findClass(providerEntity.getProviderClassFullName(),projectSearchScope);
                    // 包

                    GeneralProjectStruct projectStruct = generalRule.getProjectStruct();

                    projectStruct.setRootPath(basePath);

                    GeneralPackageStruct packageStruct = generalRule.getPackageStruct();


                    // 类
                    GeneralClassStruct classStruct = generalRule.getClassStruct();

                    // 方法
                    GeneralMethodStruct methodStruct = generalRule.getMethodStruct();

                    if (CollectionUtils.isNotEmpty(requestParamStructList)){
                        methodStruct.setRequestParamStructList(requestParamStructList);
                    }
                    // 全限定名
                    String qualifiedName = classStruct.getQualifiedName();
                    System.out.println("qualifiedName:"+qualifiedName);
                    PsiClass providerClass = JavaPsiFacade.getInstance(project).findClass(qualifiedName,projectSearchScope);
                    System.out.println("providerClass:"+providerClass);

//                PsiClass[] arraySearchPsiClass = PsiShortNamesCache.getInstance(project).getClassesByName("String", allSearchScope);
//
//                System.out.println("arraySearchPsiClass:"+arraySearchPsiClass);
//                if (arraySearchPsiClass!=null&&arraySearchPsiClass.length!=0){
//                    for (PsiClass psiClass:arraySearchPsiClass){
//                        System.out.println(JSON.toJSONString(psiClass));
//                    }
//                }

                    PsiDirectoryFactory psiDirectoryFactory = PsiJavaDirectoryFactory.getInstance(project);
                    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
                    XmlElementFactory xmlElementFactory = XmlElementFactory.getInstance(project);

                    PsiDirectoryFactory psiDirectoryFactory2 = PsiDirectoryFactory.getInstance(project);


                    // 不存在class,则创建class
                    boolean isNewClass=false;
                    if (providerClass==null){
                        try {
                            isNewClass=true;
                            VirtualFile virtualFile = null;
                            try {
                                // 区分类名或接口
                                // 接口
                                if (MyNumberUtils.equals(packageStruct.getType(),GeneralPackageStructTypeEnums.MAPPER_XML.getValue())){
                                    // XML
                                    XmlText displayText = xmlElementFactory.createDisplayText("");

                                    String packagePath = packageStruct.getPackagePath();
                                    virtualFile = VfsUtil.createDirectoryIfMissing(packagePath);
                                    PsiDirectory directory = psiDirectoryFactory2.createDirectory(virtualFile);
                                    directory.add(displayText);

                                    continue;

                                }else if (MyNumberUtils.equals(packageStruct.getType(),GeneralPackageStructTypeEnums.INTERFACE.getValue())){
                                    providerClass = factory.createInterface(classStruct.getClassFullName());
                                }else if (MyNumberUtils.equals(packageStruct.getType(),GeneralPackageStructTypeEnums.IMPLEMENTATION.getValue())
                                        ||MyNumberUtils.equals(packageStruct.getType(),GeneralPackageStructTypeEnums.CLASS.getValue())){
                                    providerClass = factory.createClass(classStruct.getClassFullName());
                                }
                                String packagePath = packageStruct.getPackagePath();
                                virtualFile = VfsUtil.createDirectoryIfMissing(packagePath);
                                PsiDirectory directory = psiDirectoryFactory.createDirectory(virtualFile);
                                directory.add(providerClass);
                                System.out.println(virtualFile);
                            } catch (Exception e) {
                                e.printStackTrace();
                                continue;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        }
                        providerClass = JavaPsiFacade.getInstance(project).findClass(qualifiedName, projectSearchScope);
                    }

                    // 查看class的父类与接口实现
                    PsiReferenceList implementsList = providerClass.getImplementsList();
                    GeneralClassStruct implementsClassStruct = classStruct.getImplementsClassStruct();
                    if (implementsClassStruct!=null){
                        PsiJavaCodeReferenceElement[] referenceElements = implementsList.getReferenceElements();
                        String implementQualifiedName = implementsClassStruct.getQualifiedName();
                        PsiJavaCodeReferenceElement referenceElement = factory.createReferenceElementByFQClassName(implementQualifiedName, allSearchScope);

                        if (referenceElements==null||referenceElements.length==0){
                            implementsList.add(referenceElement);
                        }else {
                            boolean isExist=false;
                            for(PsiJavaCodeReferenceElement element : referenceElements){
                                String qualifiedName1 = element.getQualifiedName();
                                if (StringUtils.equals(StringUtils.trim(qualifiedName1),StringUtils.trim(implementQualifiedName))){
                                    isExist=true;
                                    break;
                                }
                            }
                            if (!isExist){
                                implementsList.add(referenceElement);
                            }

                        }
                    }

                    // 继承的类
                    PsiReferenceList extendsList = providerClass.getExtendsList();
                    if (extendsList!=null){
                        ImportStruct extendsImportStruct = classStruct.getExtendsImportStruct();
                        if (extendsImportStruct!=null){
                            String extendsQualifiedName = extendsImportStruct.showQualifiedName();
                            PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements();
                            PsiJavaCodeReferenceElement referenceElement = factory.createReferenceFromText(extendsQualifiedName, providerClass);

                            //增加导入语句
                            addImportStatement(providerClass,extendsImportStruct);

                            // 查看泛型 并导入
                            List<ImportStruct> genericsClassStructList = extendsImportStruct.getGenericsClassStructList();
                            if (CollectionUtils.isNotEmpty(genericsClassStructList)){
                                for(ImportStruct importStruct:genericsClassStructList){
                                    addImportStatement(providerClass,importStruct);
                                }
                            }

                            if (referenceElements==null||referenceElements.length==0){
                                extendsList.add(referenceElement);
                            }else {
                                boolean isExist=false;
                                for(PsiJavaCodeReferenceElement element : referenceElements){
                                    String qualifiedName1 = element.getQualifiedName();
                                    if (StringUtils.equals(StringUtils.trim(qualifiedName1),StringUtils.trim(extendsImportStruct.getFullClassName()))){
                                        isExist=true;
                                        break;
                                    }
                                }
                                if (!isExist){
                                    extendsList.add(referenceElement);
                                }

                            }
                        }

                    }

                    // 加注解
                    List<ImportStruct> annotationImportStructList = classStruct.getAnnotationImportStructList();
                    if (CollectionUtils.isNotEmpty(annotationImportStructList)){
                        PsiFile psiFile = providerClass.getContainingFile();
                        PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;
                        PsiPackageStatement packageStatement = psiJavaFile.getPackageStatement();
                        if (packageStatement == null) {
                            return;
                        }
                        PsiAnnotation[] annotations = providerClass.getAnnotations();

                        PsiModifierList modifierList = providerClass.getModifierList();
                        PsiElement firstChild = modifierList.getFirstChild();

                        for (ImportStruct annotationImportStruct:annotationImportStructList){
                            //TODO 校验注解是否已经存在 已存在则不进行添加
                            PsiAnnotation psiAnnotation = factory.createAnnotationFromText("@" + annotationImportStruct.getFullClassName(), providerClass);
                            if (annotations==null||annotations.length==0){
                                providerClass.addBefore(psiAnnotation, firstChild);
                            }else {
                                boolean isExist=false;
                                for(PsiAnnotation annotation:annotations){
                                    String qualifiedName1 = annotation.getQualifiedName();
                                    if (StringUtils.equals(qualifiedName1,psiAnnotation.getQualifiedName())){
                                        isExist=true;
                                        break;
                                    }
                                }
                                if (!isExist){
                                    providerClass.addBefore(psiAnnotation, firstChild);
                                }

                            }
                        }

                    }


                    boolean isContainMethod = PsiClassUtils.containMethod(providerClass, methodName);
                    System.out.println("providerClass:"+providerClass);
                    System.out.println("isContainMethod:"+isContainMethod+",methodEntity.getName():"+methodName);
                    // 若包含则覆盖更新
                    if (isContainMethod){
                        PsiClassUtils.removeMethod(providerClass,methodName);
                    }

                    // 返回参数
                    PsiType valuePsiType=null;
                    if (returnParamStruct==null||StringUtils.isBlank(returnParamStruct.getClassName())){
                        valuePsiType = factory.createTypeFromText("void", providerClass);
                    }else {
                        valuePsiType = factory.createTypeFromText(returnParamStruct.showQualifiedName(), providerClass);
                    }

                    PsiMethod methodPsiMethod = factory.createMethod(methodName, valuePsiType);
                    // 若是接口 删除body体 只留声明
                    // 请求参数
                    List<RequestParamStruct> requestParamStructList = methodStruct.getRequestParamStructList();
                    StringBuilder requestCallBackBuilder=new StringBuilder();

                    if (CollectionUtils.isNotEmpty(requestParamStructList)){
                        for(RequestParamStruct requestParamStruct:requestParamStructList){
                            if (StringUtils.isNotBlank(requestCallBackBuilder.toString())){
                                requestCallBackBuilder.append(",");
                            }
                            requestCallBackBuilder.append(requestParamStruct.getParamName());
                        }
                    }

                    if (MyNumberUtils.equals(packageStruct.getType(), GeneralPackageStructTypeEnums.INTERFACE.getValue())){
                        methodPsiMethod.getBody().delete();
                    }else if (MyNumberUtils.equals(packageStruct.getType(), GeneralPackageStructTypeEnums.IMPLEMENTATION.getValue())){

                        PsiAnnotation overridePsiAnnotation = factory.createAnnotationFromText("@java.lang.Override\n", providerClass);

                        methodPsiMethod.addBefore(overridePsiAnnotation,methodPsiMethod.getModifierList().getFirstChild());

//                        PsiCodeBlock statement = factory.createCodeBlock();
                        PsiStatement statement =null;
                        // 引入的引用子类
                        GeneralClassStruct fieldGeneralClassStruct = classStruct.getFieldGeneralClassStruct();

                        // 有返回参数
                        if (returnParamStruct!=null&&StringUtils.isNotBlank(returnParamStruct.getClassName())){
//                            statement = factory.createStatementFromText("return;", methodPsiMethod);

                            if (fieldGeneralClassStruct==null){
                                statement = factory.createStatementFromText("return null;", methodPsiMethod);
                            }else {
                                if (fieldGeneralClassStruct.isInternalEmbedding()){
                                    statement = factory.createStatementFromText("return "+fieldGeneralClassStruct.getInternalEmbeddingFiledName()+"."+methodName+"("+requestCallBackBuilder.toString()+");", methodPsiMethod);
                                }else {
                                    // 导入子类
                                    // 校验是否已经存在属性

                                    List<String> internalAnnotationQualifiedNameList = fieldGeneralClassStruct.getInternalAnnotationQualifiedNameList();
                                    StringBuilder sb=new StringBuilder();
                                    if (CollectionUtils.isNotEmpty(internalAnnotationQualifiedNameList)){
                                        for(String annotationName:internalAnnotationQualifiedNameList){
                                            sb.append("@").append(StringUtils.trimToEmpty(annotationName)).append("\n");
                                        }
                                    }

                                    PsiField psiField = factory.createFieldFromText(sb.toString()+"private " + fieldGeneralClassStruct.getQualifiedName() + " " + fieldGeneralClassStruct.getInternalEmbeddingFiledName()+";", providerClass);

                                    PsiField[] fields = providerClass.getFields();

                                    if (fields==null||fields.length==0){
                                        PsiMethod[] methods = providerClass.getMethods();
                                        if (methods==null||methods.length==0){
                                            providerClass.add(psiField);
                                        }else {
                                            providerClass.addBefore(psiField,methods[0]);
                                        }
                                    }else {
                                        boolean isExist=false;
                                        for(PsiField psiField2:fields){
                                            String name = psiField2.getName();

                                            if (StringUtils.equals(StringUtils.trim(name),fieldGeneralClassStruct.getInternalEmbeddingFiledName())){
                                                isExist=true;
                                            }
                                        }
                                        if (!isExist){
                                            providerClass.addAfter(psiField,fields[fields.length-1]);
                                        }
                                    }
                                    statement = factory.createStatementFromText("return "+fieldGeneralClassStruct.getInternalEmbeddingFiledName()+"."+methodName+"("+requestCallBackBuilder.toString()+");", methodPsiMethod);
                                }
                            }

                        }else {
                            if (fieldGeneralClassStruct!=null){
                                if (fieldGeneralClassStruct.isInternalEmbedding()){
                                    statement = factory.createStatementFromText(fieldGeneralClassStruct.getInternalEmbeddingFiledName()+"."+methodName+"();", methodPsiMethod);
                                }else {
                                    // 导入子类
                                    List<String> internalAnnotationQualifiedNameList = fieldGeneralClassStruct.getInternalAnnotationQualifiedNameList();
                                    StringBuilder sb=new StringBuilder();
                                    if (CollectionUtils.isNotEmpty(internalAnnotationQualifiedNameList)){
                                        for(String annotationName:internalAnnotationQualifiedNameList){
                                            sb.append("@").append(StringUtils.trimToEmpty(annotationName)).append("\n");
                                        }
                                    }
                                    PsiField psiField = factory.createFieldFromText(sb.toString()+"private " + fieldGeneralClassStruct.getQualifiedName() + " " + fieldGeneralClassStruct.getInternalEmbeddingFiledName()+";", providerClass);
                                    PsiField[] fields = providerClass.getFields();

                                    if (fields==null||fields.length==0){
                                        PsiMethod[] methods = providerClass.getMethods();
                                        if (methods==null||methods.length==0){
                                            providerClass.add(psiField);
                                        }else {
                                            providerClass.addBefore(psiField,methods[0]);
                                        }
                                    }else {
                                        boolean isExist=false;
                                        for(PsiField psiField2:fields){
                                            String name = psiField2.getName();

                                            if (StringUtils.equals(StringUtils.trim(name),StringUtils.trim(fieldGeneralClassStruct.getInternalEmbeddingFiledName()))){
                                                isExist=true;
                                            }
                                        }
                                        if (!isExist){
                                            providerClass.addAfter(psiField,fields[fields.length-1]);
                                        }
                                    }
                                    statement = factory.createStatementFromText(fieldGeneralClassStruct.getInternalEmbeddingFiledName()+"."+methodName+"("+requestCallBackBuilder.toString()+");", methodPsiMethod);
                                }
                            }
                        }

                        if (statement!=null){
                            methodPsiMethod.getBody().add(statement);
                        }

                    }



                    PsiParameterList parameterList = methodPsiMethod.getParameterList();


                    // 请求参数
//                    List<RequestParamStruct> requestParamStructList = methodStruct.getRequestParamStructList();

                    // 加注释
                    String docCommentJTextFieldText="/** \n* "+StringUtils.trimToEmpty(commentJTextField.getText())+"\n*/";

                    PsiDocComment psiComment = factory.createDocCommentFromText(docCommentJTextFieldText,methodPsiMethod);

                    if (CollectionUtils.isNotEmpty(requestParamStructList)){
                        // 加入参数
                        for (RequestParamStruct requestParamStruct:requestParamStructList){
//                        PsiParameter parameter = factory.createParameter(requestParamStruct.getParamName(), factory.createTypeFromText(requestParamStruct.getPackageName() + "." + requestParamStruct.getClassName(), providerClass));
                            PsiParameter parameter = factory.createParameter(requestParamStruct.getParamName(), factory.createTypeFromText(requestParamStruct.showQualifiedName(), providerClass));
//                        PsiParameter parameter = factory.createParameterFromText(requestParamStruct.showQualifiedName(), providerClass);
                            parameterList.add(parameter);
                            String comment = StringUtils.trimToEmpty(requestParamStruct.getComment());
                            psiComment.add(factory.createParamTag(requestParamStruct.getParamName(),comment));
                        }
                    }

                    // 增加返回注释
                    if (returnParamStruct!=null){
                        String returnComment = returnParamStruct.getComment();
                        if (StringUtils.isBlank(returnComment)){
                            psiComment.add(factory.createDocTagFromText("@return"));
                        }else {
                            psiComment.add(factory.createDocTagFromText("@return "+StringUtils.trimToEmpty(returnComment)));
                        }
                    }
                    methodPsiMethod.addBefore(psiComment,methodPsiMethod.getFirstChild());
                    // 加注释
                    if (MyNumberUtils.equals(packageStruct.getType(),GeneralPackageStructTypeEnums.INTERFACE.getValue())
                       ||MyNumberUtils.equals(packageStruct.getType(),GeneralPackageStructTypeEnums.IMPLEMENTATION.getValue())){
                        providerClass.add(methodPsiMethod);
                    }

                    PsiClassUtils.formatJavaCode(providerClass);

                }
            }
        });


    }

    /**
     * 添加import语句
     * @param psiClass
     */
    private void addImportStatement(PsiClass psiClass,ImportStruct importStruct){
//        String qualifiedClassName = importStruct.showQualifiedName();
        String qualifiedClassName = importStruct.getFullClassName();

        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        GlobalSearchScope allSearchScope=GlobalSearchScope.allScope(project);
        PsiImportStatement psiImportStatement = factory.createImportStatement(JavaPsiFacade.getInstance(project).findClass(qualifiedClassName, allSearchScope));

        PsiFile psiFile = psiClass.getContainingFile();
        PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;


        PsiImportList importList = psiJavaFile.getImportList();

        if (importList==null){
            return;
        }

        PsiImportStatement singleClassImportStatement = importList.findSingleClassImportStatement(qualifiedClassName);
        if (singleClassImportStatement!=null){
            return;
        }
        PsiImportStatement onDemandImportStatement = importList.findOnDemandImportStatement(importStruct.getPackageName());
        if (onDemandImportStatement!=null){
            return;
        }
        //校验是否
        importList.add(psiImportStatement);
    }



}
